﻿angular.module('Caltech').controller('workOrderItemController', function ($scope, Restangular, $state, $stateParams, Roles, toaster, Constants, $filter, ServicePlaces, ProcessStatusWO) {
    'use strict';

    var defaulModel = {
        customer: {
        },
        salesman: {
        },
        technician: {},
        calibrationCycle: 6,
        calibrationDate: new Date(),
        workOrderDetails: [],
        showFullName: false,
        createdBy: Constants.accountInfo.id,
        updatedBy: Constants.accountInfo.id
    };

    $scope.pageCount = 1;
    $scope.user = Constants.accountInfo;
    $scope.showFullName = false;

    $scope.Cycles = [
        {
            value: 6,
            text: '6 months'
        },
        {
            value: 12,
            text: '12 months'
        },
        {
            value: 24,
            text: '24 months'
        }
    ];

    $scope.model = defaulModel;

    if ($stateParams.id) {
        Restangular.one('workOrder', $stateParams.id).get().then(function (model) {
            $scope.model = model;
            model.calibrationDate = new Date(model.calibrationDate);
            model.updatedBy = Constants.accountInfo.id;
        });
    }

    $scope.$watchCollection('[model.calibrationCycle, model.calibrationDate]', function (newCollection, oldCollection, scope) {
        $scope.model.nextDueDate = new Date($scope.model.calibrationDate.getTime());
        $scope.model.nextDueDate.setMonth($scope.model.nextDueDate.getMonth() + $scope.model.calibrationCycle * 1);
    });

    $scope.$watch('model.workOrderDetails', function () {
        if ($scope.model && $scope.model.workOrderDetails) {
            //$scope.tempTotalPrice = $scope.model.items.reduce(function (previousValue, item) {
            //    return previousValue + (item.quantity * item.unitPrice);
            //}, 0);

            $scope.totalAmount = $scope.model.workOrderDetails.reduce(function (previousValue, item) {
                return previousValue + item.quantity;
            }, 0);
        }

    }, true);

    $scope.getQuoteList = function (poNumber) {
        return Restangular
            .all('quote').getList({
                quoteNumber: poNumber
            });
    };

    $scope.getPOList = function (poNumber) {
        return Restangular
            .all('po').getList({
                poNumber: poNumber
            });
    };

    $scope.updateEquipment = function (item) {
        if (typeof (item) === 'object') {
            $scope.model.poNumber = item.poNumber;

            Restangular.one('customer', item.companyId)
                .get()
                .then(function (customer) {
                    $scope.model.company = customer;
                });

            Restangular.one('user', item.salesmanId)
               .get()
               .then(function (user) {
                   $scope.model.salesman = user;
               });

            Restangular.one('po', item.id)
              .get()
              .then(function (po) {
                  $scope.model.workOrderDetails = po.items;
                  $scope.model.calibrationDate = new Date(po.calibrationDate);
              });
        }
    };


    $scope.update = function (model) {
        model.companyId = model.company.id;
        model.salesmanId = model.salesman.id;
        model.technicianId = model.technician ? model.technician.id : undefined;
        model.company = undefined;
        model.salesman = undefined;
        model.technician = undefined;

        return model.put({ id: model.workOrderId }).then(function () {
            $state.forceReload();
        });
    };

    $scope.save = function (model) {
        model.companyId = model.company.id;
        model.salesmanId = model.salesman.id;
        model.technicianId = model.technician.id;
        model.company = undefined;
        model.salesman = undefined;
        model.technician = undefined;
        model.createdBy = Constants.accountInfo.id;
        return Restangular.all('workOrder').post(model).then(function (id) {
            $state.go('workOrder-item', { id: id });
        });
    };

    $scope.remove = function (model) {
        return model.remove({ id: model.workOrderId }).then(function () {
            history.back();
        });
    };

    $scope.servicePlaces = ServicePlaces.map(function (value) {
        var ordinal = $filter('ordinal');
        value.text = ordinal(value.text).replace('K L', 'KL');
        return value;
    });

    $scope.showServicePlaces = function (value) {
        var result = '';

        if (value) {
            var selected = $filter('filter')($scope.servicePlaces, { value: value });

            if (selected.length) {
                result = selected[0].text;
            }
        }

        return result;
    };

    $scope.status = ProcessStatusWO.map(function (value) {
        var ordinal = $filter('ordinal');
        value.text = ordinal(value.text);
        return value;
    });

    $scope.showStatus = function (value) {
        var result = '';
        if (value) {
            var selected = $filter('filter')($scope.status, { value: value });
            if (selected.length) {
                result = selected[0].text;
            }
        }
        return result;
    };

    $scope.goToCertificate = function (equipmentId, customerId) {
        $state.go('certificate-new', { equipmentId: equipmentId, customerId: customerId, woNo: $scope.model.workOrderNo, poNo: $scope.model.poNumber });
    };

    if ($stateParams.poId > 0) {
        $scope.model.poId = $stateParams.poId;
        Restangular.one('po', $stateParams.poId).get().then(function (item) {
            $scope.updateEquipment(item);
        });
    }

    $scope.removeRow = function (index) {
        $scope.model.workOrderDetails.splice(index, 1);
    };

});